import React, {Component} from 'react';
import {Link, routerRedux} from 'dva/router'
import Debounce from 'lodash-decorators/debounce';
import {connect} from 'dva';
import {Avatar, Badge, Button, Card, Col, Divider, Icon, Rate, Row, Steps, Table} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import UserPointChangeModal from '../../components/user/UserPointChangeModal';
import UserMoneyChangeModal from '../../components/user/UserMoneyChangeModal';
import styles from './UserDetail.less';
import UserEditModal from "../../components/user/UserEditModal";
import PhotoItem from "../../components/Photo/index";

const {Step} = Steps;
const {Description} = DescriptionList;
const ButtonGroup = Button.Group;

const getWindowWidth = () => (window.innerWidth || document.documentElement.clientWidth);

const tabList = [{
  key: 'logs',
  tab: '变动记录',
}, {
  key: 'charge',
  tab: '充值记录',
}, {
  key: 'point',
  tab: '积分记录',
}
];

const columns = [{
  title: '类型',
  dataIndex: 'type_text',
  key: 'type_text',
}, {
  title: '金额',
  dataIndex: 'money',
  key: 'money',
}, {
  title: '信息',
  dataIndex: 'type_label',
  key: 'type_label',
  render: text => (
    <Badge status="success" text={text}/>
  ),
},
  {
    title: '备注',
    dataIndex: 'message',
    key: 'message'
  },
  {
    title: '记录时间',
    dataIndex: 'created_at',
    key: 'created_at',
  },];


const pointColumns = [{
  title: '类型',
  dataIndex: 'type_text',
  key: 'type_text',
}, {
  title: '积分',
  dataIndex: 'point',
  key: 'point',
}, {
  title: '信息',
  dataIndex: 'remark',
  key: 'remark',
  render: text => (
    <Badge status="success" text={text}/>
  ),
},

  {
    title: '记录时间',
    dataIndex: 'created_at',
    key: 'created_at',
  },];


const chargeColumns = [{
  title: '充值单号',
  dataIndex: 'order_no',
  key: 'order_no',
}, {
  title: '金额',
  dataIndex: 'money',
  key: 'money',
}, {
  title: '状态',
  dataIndex: 'status',
  key: 'status',
  render: text => (
    text === 1 ? <Badge status="success" text="已充值"/> : <Badge status="error" text="未付款"/>
  ),
}, {
  title: '记录时间',
  dataIndex: 'created_at',
  key: 'created_at',
},];

const friendsColumns = [{
    title: '昵称',
    dataIndex: 'name',
    key: 'name',
}, {
    title: '头像',
    dataIndex: 'avatar',
    key: 'avatar',
    render: (vale) => (
        <Avatar src={vale}/>
    )
},
    {
        title: '真实姓名',
        dataIndex: 'true_name',
        key: 'true_name',
        render: (vale,record) => (
            <p>{record.info.true_name}</p>
        )
    },
    {
        title: '地址',
        dataIndex: 'address',
        key: 'address',
        render: (vale,record) => (
            <p>{record.info.address}</p>
        )
    },
    {
    title: '工种',
    dataIndex: 'service_type',
    key: 'service_type',
    render: text => (
        <Badge status="success" text={text}/>
    ),
},
    {
        title: '电话',
        dataIndex: 'phone',
        key: 'phone',
    },
    {
        title: '是否闲工',
        dataIndex: 'support_status',
        key: 'support_status',
    },
];


@connect(state => ({
  profile: state.profile,
  user: state.user
}))
export default class UserDetail extends Component {
  state = {
    operationkey: 'logs',
    stepDirection: 'horizontal',
    thumbUrl: ''

  }

  loadChecks = () => {
    const {dispatch, match} = this.props;
    const id = match.params.id
    dispatch({
      type: 'user/fetchChanges',
      payload: {user_id: id},
      callback: () => {
      }
    });
  }

  loadMoney = () => {
    const {dispatch, match} = this.props;
    const id = match.params.id
    dispatch({
      type: 'profile/fetchProfile',
      payload: {id: id},
      callback: () => {
        dispatch({
          type: 'profile/fetchFriends',
          payload: {user_id: id}
        })
      }
    });
    dispatch({
      type: 'profile/fetchCharge',
      payload: {user_id: id}
    });
    dispatch({
      type: 'profile/fetchMoney',
      payload: {user_id: id}
    });
  }

    loadPoint = () => {
        const {dispatch, match} = this.props;
        const id = match.params.id
        dispatch({
            type: 'profile/fetchProfile',
            payload: {id: id},
            callback: () => {
                dispatch({
                    type: 'profile/fetchFriends',
                    payload: {user_id: id}
                })
            }
        });
        dispatch({
            type: 'profile/fetchPoint',
            payload: {user_id: id}
        });
    }

    loadProfile = () => {
        const {dispatch, match} = this.props;
        const id = match.params.id
        dispatch({
            type: 'profile/fetchProfile',
            payload: {id: id},
            callback: () => {
                dispatch({
                    type: 'profile/fetchFriends',
                    payload: {user_id: id}
                })
            }
        });
    }

  componentDidMount() {
    const {dispatch, match} = this.props;
    const id = match.params.id
    dispatch({
      type: 'profile/fetchProfile',
      payload: {id: id}
    });
    dispatch({
      type: 'profile/fetchCharge',
      payload: {user_id: id}
    });
    dispatch({
      type: 'profile/fetchMoney',
      payload: {user_id: id}
    });
    dispatch({
      type: 'profile/fetchPoint',
      payload: {user_id: id}
    });
    this.loadChecks()
    this.setStepDirection();
    window.addEventListener('resize', this.setStepDirection);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.setStepDirection);
  }

  onOperationTabChange = (key) => {
    this.setState({operationkey: key});
  }
  CouponClick = () => {
    const {dispatch, match} = this.props;
    let id = match.params.id;

    dispatch(routerRedux.push({pathname: `/manager/${id}/coupon`, query: {user_id: id}}))
  }

  handlePointTableChange = (pagination, filters, sorter) => {
    const {dispatch, match} = this.props;
    const id = match.params.id
    dispatch({
      type: 'profile/fetchPoint',
      payload: {user_id: id, page: pagination.current, size: pagination.size}
    });
  }
  handleChecksTableChange = (pagination, filters, sorter) => {
    const {dispatch, match} = this.props;
    const id = match.params.id

    dispatch({
      type: 'user/fetchChanges',
      payload: {user_id: id, page: pagination.current, size: pagination.size}
    });
  }
  handleChargeTableChange = (pagination, filters, sorter) => {
    const {dispatch, match} = this.props;
    const id = match.params.id
    dispatch({
      type: 'profile/fetchCharge',
      payload: {user_id: id, page: pagination.current, size: pagination.size}
    });
  }
  handleMoneyTableChange = (pagination, filters, sorter) => {
    const {dispatch, match} = this.props;
    const id = match.params.id
    dispatch({
      type: 'profile/fetchMoney',
      payload: {user_id: id, page: pagination.current, size: pagination.size}
    });
  }
  @Debounce(200)
  setStepDirection = () => {
    const {stepDirection} = this.state;
    const w = getWindowWidth();
    if (stepDirection !== 'vertical' && w <= 576) {
      this.setState({
        stepDirection: 'vertical',
      });
    } else if (stepDirection !== 'horizontal' && w > 576) {
      this.setState({
        stepDirection: 'horizontal',
      });
    }
  }
  prewThumb = (url) => {

  }

  handleStatus = (status, item) => {
    const {dispatch} = this.props
    this.props.dispatch({
      type: 'user/status',
      payload: {
        status: status == 0 ? 1 : 0,
        items: [item],
      },
      callback: () => {
        dispatch({
          type: 'profile/fetchProfile',
          payload: {id: item.id}
        });
      },
    });
  }
  handleChangeInfo = () => {
    console.log('基本信息')
    this.props.dispatch({
      type: 'user/changeVisible',
      payload: true,
      callback: () => {
        console.log('回调');
      },
    });
  }
  changeCheck = (id, status) => {
    console.log('check');
    this.props.dispatch({
      type: "user/changeServiceCheck",
      payload: {
        id: id,
        status: status,
      }, callback: () => {
        this.loadChecks()
      }
    })
  }


  render() {
    const {stepDirection} = this.state;
    const {profile, user: {changes}} = this.props;
    const {info} = profile.user;
    const {advancedLoading, chargeLogs, moneyLogs,friends, pointLogs} = profile;
    const checkColumns = [{
      title: '编号',
      dataIndex: 'id',
      key: 'id',
    }, {
      title: '提交时间',
      dataIndex: 'created_at',
      key: 'created_at',
    }, {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: text => {
        switch (Number(text)) {
          case 0:
            return (<Badge status="progress" text="等待审核"/>)
            break;
          case 1:
            return (<Badge status="success" text="已通过"/>)
            break;
          case 2:
            return (<Badge status="error" text="已驳回"/>)
            break;
        }
      },
    }, {
      title: '资质证明',
      dataIndex: 'prove',
      key: 'prove',
      render: (text) => (<PhotoItem src={`https://zzbj.kooki.cn/${text}`}/>)
    },
      {
        title: '审核时间',
        dataIndex: 'check_at',
        key: 'check_at',
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, record) => {
          return (<ButtonGroup>
            <Button disalbed={record.status !== 0} onClick={() => {
              this.changeCheck(record.id, 1)
            }}>通过审核</Button>
            <Button disalbed={record.status !== 0} onClick={() => {
              this.changeCheck(record.id, 2)
            }}>驳回审核</Button>
          </ButtonGroup> )
        }
      },
    ];
    const contentList = {
      logs: <Table
        rowKey={record => record.id}
        pagination={moneyLogs.pagination}
        loading={advancedLoading}
        dataSource={moneyLogs.list}
        onChange={this.handleMoneyTableChange}
        columns={columns}
      />,
      charge: <Table
        rowKey={record => record.id}
        pagination={chargeLogs.pagination}
        loading={advancedLoading}
        dataSource={chargeLogs.list}
        onChange={this.handleChargeTableChange}
        columns={chargeColumns}
      />,
      point: <Table
        rowKey={record => record.id}
        pagination={pointLogs.pagination}
        loading={advancedLoading}
        dataSource={pointLogs.list}
        onChange={this.handlePointTableChange}
        columns={pointColumns}
      />
    };

    const description = (
      <DescriptionList className={styles.headerList} size="small" col="2">
        <Description term="用户类型">{profile.user.role_label}</Description>
        <Description term="手机">{profile.user.phone}</Description>
        <Description term="性别">{profile.user.sex === 'man' ? '男' : '女'}</Description>
        <Description term="注册时间">{profile.user.created_at}</Description>
        <Description term="用户状态"><Badge
          status={profile.user.status === 1 ? 'processing' : 'error'}/>{profile.user.status_label}
        </Description>
        <Description term="简介">{profile.user.description}</Description>
      </DescriptionList>
    );
    const action = (
      <div>
        <ButtonGroup>
          <Button onClick={() => this.handleChangeInfo()}>修改信息</Button>
          <Button
            onClick={() => this.handleStatus(profile.user.status, profile.user)}>{profile.user.status == 0 ? '启用' : '拉黑'}</Button>

          <Button onClick={() => {
            this.props.dispatch({type: "profile/changeModal", payload: {pointAddShow: true}})
          }}>积分管理</Button>
        </ButtonGroup>
        <Button onClick={() => {
          this.props.dispatch({type: "profile/changeModal", payload: {moneyAddShow: true}})
        }} type="primary">余额管理</Button>
      </div>
    );
    const extra = (
      <Row>
        <Col xs={24} sm={12}>
          <div className={styles.textSecondary}>积分</div>
          <div className={[styles.heading]} style={{color: '#ff8c00'}}>{profile.user.point}</div>
        </Col>
        <Col xs={24} sm={12}>
          <div className={styles.textSecondary}>余额</div>
          <div className={styles.heading} style={{color: '#f03a30'}}>¥ {profile.user.money}</div>
        </Col>
      </Row>
    );

    return (
      <PageHeaderLayout
        title={profile.user.name}
        logo={<Avatar alt="" src={profile.user.avatar}/>}
        action={action}
        content={description}
        extraContent={extra}

      >


        <Card title="服务认证修改" style={{marginBottom: 24}} bordered={false}>

          <Table style={{marginTop: 24}} rowKey={record => record.id}
                 pagination={changes.pagination}
                 loading={advancedLoading}
                 dataSource={changes.list}
                 onChange={this.handleChecksTableChange}
                 columns={checkColumns}/>
        </Card>

        <Card
          className={styles.tabsCard}
          bordered={false}
          tabList={tabList}
          onTabChange={this.onOperationTabChange}
        >
          {contentList[this.state.operationkey]}
        </Card>
        {profile.user.role == 'vip' ? ( <Card title="师傅信息" style={{marginBottom: 24}} bordered={false}>
          <DescriptionList style={{marginBottom: 24}}>
            <Description term="真实姓名">{info ? info.true_name : ''}</Description>
            <Description term="身份证号">{info ? info.id_card_code : ''}</Description>
            <Description term="手机">{info ? profile.user.phone : ''}</Description>
            <Description term="服务类型">{info ? profile.user.phone : ''}</Description>
            <Description term="联系地址"><a href="api.baid">{info ? info.address : ''}</a></Description>
          </DescriptionList>
          <Row gutter={16} style={{marginBottom: 24}} title="身份证信息">
            <Col span={6}><PhotoItem title="身份证正面" width={120}
                                     src={info ? `https://zzbj.kooki.cn/${info.id_card_for}` : ''}/></Col>
            <Col span={6}><PhotoItem title="身份证背面" width={120}
                                     src={info ? `https://zzbj.kooki.cn/${info.id_card_back}` : ''}/></Col>
            <Col span={6}><PhotoItem width={120}
                                     title="手持身份证"
                                     src={info ? `https://zzbj.kooki.cn/${info.handle_card}` : ''}/></Col>
            <Col span={6}><PhotoItem width={120}
                                     title="资质证明"
                                     src={info ? `https://zzbj.kooki.cn/${info.id_card_for}` : ''}/></Col>
          </Row>
          <h4 style={{marginBottom: 16}}>详细信息</h4>
          <Card type="inner" title="师傅详细信息">
            <DescriptionList size="small" col="2" style={{marginBottom: 16}} title="服务评分">
              <Description term="平均评分"><Rate disabled defaultValue={info ? info.star : 0}/></Description>
              <Description term="速度"><Rate disabled defaultValue={info ? info.speed : 0}/></Description>

              <Description term="精细度"><Rate disabled
                                            defaultValue={info ? info.fineness : 0}/></Description>

              <Description term="服务态度"><Rate disabled
                                             defaultValue={info ? info.attitude : 0}/></Description>

              <Description term="综合质量"><Rate disabled
                                             defaultValue={info ? info.quality : 0}/></Description>
              <Description term="综合满意度"><Rate disabled defaultValue={info ? info.sat : 0}/></Description>

                        </DescriptionList>
                        <Divider style={{margin: '16px 0'}}/>
                        <DescriptionList size="small" style={{marginBottom: 16}} title="服务相关信息" col="1">
                            <Description term="服务单数">
                                共服务{info ? info.service_count : 0}单
                            </Description>
                            <Description term="服务类别">
                                {info ? profile.user.service_type : ''}
                            </Description>
                            <Description term="服务时间">
                                {info ? info.work_time : ''}
                            </Description>
                            <Description term="是否工长">
                                {info ? (info.worker_leader == 1 ? "是" : '否') : ''}
                            </Description>
                        </DescriptionList>
                        <Divider style={{margin: '16px 0'}}/>
                    </Card>
                </Card>) : null}
                {profile.user.role == 'vip' ? (
                    <Card title="师傅工友" style={{marginBottom: 24}} bordered={false}>
                        <Table
                            columns={friendsColumns}
                            rowKey={record => record.id}
                            loading={advancedLoading}
                            dataSource={friends}
                        />
                    </Card>
                ) : null}
                <UserEditModal onChangeUser={() => {
                    this.loadProfile()
                }} item={profile.user}/>
                <UserPointChangeModal onPointChange={this.loadPoint} user={profile.user}/>
                <UserMoneyChangeModal onMoneyChange={this.loadMoney} user={profile.user}/>
            </PageHeaderLayout>
        );
    }
}
